# Copyright (c) 2011, 2012 Nathan Grubb
# Available under the new BSD license; see LICENSE.txt

"""lib/connection.py: Contains the Connection object, which is used by the bot
   to handle the IRC connection centrally.
"""

import socket

import lib.message

class Connection(object):
    """Connection object. All interactions with the network are handled
       through this class.
    """

    def __init__(self, grubbot):
        self.grubbot = grubbot
        self.buffer = ""

    def connect(self, host, port):
        # Note: create_connection automatically connects
        self.connection = socket.create_connection((host, port))

    def close(self):
        self.connection.close()

    def read(self):
        """Reads one line from the server, blocking until one is available."""

        while True:
            if "\r\n" in self.buffer:
                line, self.buffer = self.buffer.split("\r\n", 1)
                print "[Recv]", line
                return line
                
            self.buffer += self.connection.recv(512) # 512 bytes is the max IRC
                                                     # line size

    def write(self, line):
        """Writes one line to the server, automatically adding a linebreak."""

        print "[Send]", line.rstrip("\n")
        self.connection.send(line + "\r\n")

    def send(self, command, *args):
        """A more convenient way to write to the server, as it builds a
           message object and converts it into a raw line to send to the server.

           Note that clients cannot send prefixes.
        """

        self.write(str(lib.message.Message(command, args)))